# 爬取百度地图POI

import requests
import json
import time
import xlwt

# TODO 输入城市
city = input("输入城市")
# TODO 输入搜索内容
serch = input("输入要查询的内容")
# TODO 输入密钥
keybaidu = "申请的密钥key"
title = []  # 标题
address = []  # 详细地址
tel = []  # 电话
lat = []  # 经度
lng = []  # 纬度
index = 0
while True:
    num = str(index)
    # 含时间戳的url，请求头
    # http://api.map.baidu.com/place/v2/search?query=旅游景点&page_size=20&page_num=1&region=大理市&output=json&ak=申请的密钥key
    url = "http://api.map.baidu.com/place/v2/search?query="+serch + \
        "&page_size=20&page_num="+num+"&region="+city+"&output=json&ak="+keybaidu+""
    print(url)
    r = requests.get(url)
    print(r.text)  # 输出json数据
    a = json.loads(r.text)  # 解析json文件,strict=False
    print(a["status"])
    if a["status"] == 401:  # 401错误跳出循环
        continue
    else:
        print(len(a["results"]))
        if len(a["results"]) == 0:
            break
        else:
            for i in range(len(a["results"])):
                if ("telephone" in a["results"][i]):
                    telephone = a["results"][i]["telephone"]
                else:
                    telephone = "无"
                title.append(a["results"][i]["name"])
                if ("address" in a["results"][i]):
                    addr = a["results"][i]["address"]
                else:
                    addr = '无'
                address.append(addr)
                tel.append(telephone)
                lat.append(a["results"][i]["location"]["lat"])
                lng.append(a["results"][i]["location"]["lng"])
            title = title
            address = address
            tel = tel
            lat = lat
            lng = lng
            index = index+1
            # time.sleep(10) #1.5s执行一次 防止并发超额
f = xlwt.Workbook()  # 创建工作簿
sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  # 创建sheet
j = 0
for title1, address1, tel1, lat1, lng1\
        in zip(title, address, tel, lat, lng):
    sheet1.write(j, 0, title1)
    sheet1.write(j, 1, address1)
    sheet1.write(j, 2, tel1)
    sheet1.write(j, 3, lat1)
    sheet1.write(j, 4, lng1)
    j = j+1
f.save(r"../"+city+serch+".xls")  # 保存文件，
# time.sleep(1.5)
